package com.cskaoyan.market.controller.wx;

import com.cskaoyan.market.config.AliyunConfig;
import com.cskaoyan.market.db.domain.MarketStorage;
import com.cskaoyan.market.service.wx.CloudService;
import com.cskaoyan.market.service.wx.WXStorageService;
import com.cskaoyan.market.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @ClassName WxStorageController
 * @Description     图片上传
 * @Author MZ
 * @Date 2023/5/22 17:47
 */
@RestController
@RequestMapping("wx/storage")
public class WxStorageController {

    @Autowired
    CloudService cloudService;
    @Autowired
    AliyunConfig aliyunConfig;
    @Autowired
    WXStorageService wxStorageService;

    // https://{bucketName}.{endPoint}/filename
    @PostMapping("upload")
    public Object upload(MultipartFile file) throws IOException {
        // 文件名
        String fileName = file.getOriginalFilename();

        // 获取后缀名
        int index = fileName.indexOf(".");
        String suffix = fileName.substring(index);
        //获取文件的mime类型
        String contentType = file.getContentType();
        // 大小
        int size = (int) file.getSize();
        // 新文件名 ：随机文件名+后缀
        String key = UUID.randomUUID().toString() + suffix;
        InputStream inputStream = file.getInputStream();
        // 使用阿里云上传
        String name = cloudService.upload(key, inputStream);

        // 写入数据库
        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setKey(key);
        marketStorage.setName(fileName);
        marketStorage.setType(contentType);
        marketStorage.setSize(size);
        // https://{bucketName}.{endPoint}/filename
        String bucketName = aliyunConfig.getOss().getBucketName();
        String endPoint = aliyunConfig.getOss().getEndPoint();
        marketStorage.setUrl("https://" + bucketName +"."+ endPoint +"/" + name);
        marketStorage.setAddTime(LocalDateTime.now());
        marketStorage.setUpdateTime(LocalDateTime.now());
        marketStorage.setDeleted(false);

        // 执行操作
        int row = wxStorageService.addStorage(marketStorage);

        if (row != 1){
            // 添加失败
            return ResponseUtil.badArgument();
        }
        return ResponseUtil.ok(marketStorage);
    }

}
